from wordcloud import WordCloud
from PIL import Image
import numpy as np

# 读取文本文件
with open('hlm.txt', 'r', encoding='utf-8') as file:
    text = file.read()

# 创建一个WordCloud对象，设置参数
wordcloud = WordCloud(
    font_path='simhei.ttf',  # 使用中文字体，确保生成的词云中文显示正常
    background_color='white',  # 背景颜色为白色
    width=800, height=600,     # 词云图片尺寸
    max_words=100,             # 最大显示词数
    colormap='Reds'            # 颜色映射，红色系
)

# 生成词云
wordcloud.generate(text)

# 选择一张图片作为词云形状
mask = np.array(Image.open("cloud_shape.png"))

# 将词云应用到图片上，设置词云形状
wordcloud = WordCloud(
    font_path='simhei.ttf',
    background_color='white',
    width=800, height=600,
    max_words=100,
    colormap='Reds',
    mask=mask  # 设置词云形状
).generate(text)

# 显示词云
import matplotlib.pyplot as plt
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')  # 隐藏坐标轴
plt.show()
